#include "userregister.h"
#include "ui_userregister.h"
#include <QMessageBox>

UserRegisterWindow::UserRegisterWindow(QWidget *parent)
    : QWidget(parent)
    , userregisterwindowUi(new Ui::UserRegisterWindow)
    , networkManager(new NetworkManager(this))
{
    userregisterwindowUi->setupUi(this);
    userregisterwindowUi->roleComboBox->addItems({"user", "admin"});
    connect(networkManager, &NetworkManager::registerResponseReceived, this, &UserRegisterWindow::handleRegisterResponse);
}

UserRegisterWindow::~UserRegisterWindow()
{
    delete userregisterwindowUi;
}

void UserRegisterWindow::on_registerButton_clicked()
{
    QString username = userregisterwindowUi->usernamelineEdit->text();
    QString password = userregisterwindowUi->passwordlineEdit->text();
    QString confirmPassword = userregisterwindowUi->comfirmPasswdLineEdit->text();
    QString role = userregisterwindowUi->roleComboBox->currentText();

    if (username.isEmpty() || password.isEmpty())
        return;

    if (password != confirmPassword) {
        QMessageBox::warning(this, "错误", "密码和确认密码不匹配");
        return;
    }

    QJsonObject json;
    json["username"] = username;
    json["password"] = password;
    json["role"] = role;
    networkManager->registerUser(json);
}

void UserRegisterWindow::on_resetButton_clicked()
{
    userregisterwindowUi->usernamelineEdit->clear();
    userregisterwindowUi->passwordlineEdit->clear();
    userregisterwindowUi->comfirmPasswdLineEdit->clear();
    userregisterwindowUi->roleComboBox->clear();
}

void UserRegisterWindow::handleRegisterResponse(const QJsonObject &response) {
    int code = response.value("code").toInt();
    QString desc = response.value("desc").toString();

    if (code == 200) {
        QMessageBox::information(this, "注册成功", desc);
    } else {
        QMessageBox::warning(this, "注册失败", desc);
    }
}
